package cz.proks.schoolpupilbook.gwt.core.handler;

import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;

import cz.proks.schoolpupilbook.gwt.core.CookieHelper;
import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.service.UserService;
import cz.proks.schoolpupilbook.gwt.widget.common.LoginForm;
import cz.proks.schoolpupilbook.shared.Constants;
import cz.proks.schoolpupilbook.shared.domain.User;

public class LoginHandler implements LoginForm.SubmitEvent.SubmitEventHandler {

	@Override
	public void onSubmit(LoginForm.SubmitEvent event) {
		Cookies.removeCookie(Constants.Cookie.USER);
		
		UserService loginService = ServiceFactory.getUserService();
		loginService.login(event.getLogin(), event.getPassword(), new ResultNotifiable<User>() {			
			@Override
			public void onSucces(User object) {
				if (object != null) {
					Cookies.setCookie(Constants.Cookie.USER, CookieHelper.asCookie(object));
					Cookies.setCookie(Constants.Cookie.USER_LOGGED, "true");
					
					History.fireCurrentHistoryState();
				}
			}
			
			@Override
			public void onError(Throwable t) {}
		});		
	}
}
